package com.fuint.module.backendApi.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fuint.common.dto.*;
import com.fuint.common.service.ExamReceiveService;
import com.fuint.common.util.TokenUtil;
import com.fuint.framework.web.BaseController;
import com.fuint.framework.web.ResponseObject;
import com.fuint.common.Constants;
import com.fuint.common.enums.StatusEnum;
import com.fuint.common.service.ExamMemberService;
import com.fuint.framework.pagination.PaginationRequest;
import com.fuint.framework.pagination.PaginationResponse;
import com.fuint.framework.exception.BusinessCheckException;
import com.fuint.repository.mapper.MtDeviceItemMapper;
import com.fuint.repository.mapper.MtDeviceRecordMapper;
import com.fuint.repository.mapper.MtExamRecordMapper;
import com.fuint.repository.model.MtDeviceItem;
import com.fuint.repository.model.MtDeviceRecord;
import com.fuint.repository.model.MtExamMember;
import com.fuint.repository.model.MtExamRecord;
import com.fuint.utils.StringUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 成员信息表管理类controller
 *
 * Created by fqs
 * CopyRight https://www.fuint.cn
 */
@Api(tags="管理端-成员信息表相关接口")
@RestController
@AllArgsConstructor
@RequestMapping(value = "/backendApi/exam_member")
public class BackendExamMemberController extends BaseController {

    /**
     * 成员信息表服务接口
     */
    private ExamMemberService examMemberService;


    private ExamReceiveService examReceiveService;


    private MtExamRecordMapper examRecordMapper;

    private MtDeviceRecordMapper mtDeviceRecordMapper;

    private MtDeviceItemMapper mtDeviceItemMapper;


    @ApiOperation(value = "体检数据对接")
    @RequestMapping(value = "/receive", method = RequestMethod.POST)
    @CrossOrigin
    public ResponseEntity<Map<String, Object>> receiveExamData(@RequestBody ExamDataDTO2 dto) {Map<String, Object> response = new HashMap<>();
        try {
            examReceiveService.saveExamData(dto);
            response.put("success", true);
            response.put("message", null);
        } catch (Exception e) {
            response.put("success", false);
            response.put("message", e.getMessage());
        }
        return ResponseEntity.ok(response);
    }

    /**
     * 成员信息表列表查询
     *
     * @param  request HttpServletRequest对象
     * @return 成员信息表列表
     */
    @ApiOperation(value = "成员信息表列表查询")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('exam_member:list')")
    public ResponseObject list(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        Integer page = request.getParameter("page") == null ? Constants.PAGE_NUMBER : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));
        String title = request.getParameter("title");
        String status = request.getParameter("status");
        String searchStoreId = request.getParameter("storeId");

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        Integer storeId = accountInfo.getStoreId();

        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(page);
        paginationRequest.setPageSize(pageSize);

        Map<String, Object> params = new HashMap<>();
        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            params.put("merchantId", accountInfo.getMerchantId());
        }
        if (StringUtil.isNotEmpty(title)) {
            params.put("title", title);
        }
        if (StringUtil.isNotEmpty(status)) {
            params.put("status", status);
        }
        if (StringUtil.isNotEmpty(searchStoreId)) {
            params.put("storeId", searchStoreId);
        }
        if (storeId != null && storeId > 0) {
            params.put("storeId", storeId);
        }
        paginationRequest.setSearchParams(params);
        PaginationResponse<MtExamMember> paginationResponse = examMemberService.queryExamMemberListByPagination(paginationRequest);

        Map<String, Object> paramsStore = new HashMap<>();
        paramsStore.put("status", StatusEnum.ENABLED.getKey());
        if (accountInfo.getStoreId() != null && accountInfo.getStoreId() > 0) {
            paramsStore.put("storeId", accountInfo.getStoreId().toString());
        }
        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            paramsStore.put("merchantId", accountInfo.getMerchantId());
        }

        Map<String, Object> result = new HashMap<>();
        result.put("paginationResponse", paginationResponse);

        return getSuccessResult(result);
    }

    /**
     * 更新成员信息表状态
     *
     * @return
     */
    @ApiOperation(value = "更新成员信息表状态")
    @RequestMapping(value = "/updateStatus", method = RequestMethod.POST)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('exam_member:edit')")
    public ResponseObject updateStatus(HttpServletRequest request, @RequestBody Map<String, Object> params) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        String status = params.get("status") != null ? params.get("status").toString() : StatusEnum.ENABLED.getKey();
        Integer id = params.get("id") == null ? 0 : Integer.parseInt(params.get("id").toString());

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);

        MtExamMember mtExamMember = examMemberService.queryExamMemberById(id);
        if (mtExamMember == null) {
            return getFailureResult(201);
        }

        String operator = accountInfo.getAccountName();
//        mtExamMember.setOperator(operator);
        mtExamMember.setStatus(status);
        examMemberService.updateExamMember(mtExamMember);

        return getSuccessResult(true);
    }

    /**
     * 保存成员信息表
     *
     * @param request HttpServletRequest对象
     * @return
     */
    @ApiOperation(value = "保存成员信息表")
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('exam_member:add')")
    public ResponseObject saveHandler(HttpServletRequest request, @RequestBody Map<String, Object> params) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        String id = params.get("id") == null ? "" : params.get("id").toString();
        String status = params.get("status") == null ? "" : params.get("status").toString();
        String storeId = params.get("storeId") == null ? "0" : params.get("storeId").toString();

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);

        MtExamMember info = new MtExamMember();
//        info.setOperator(accountInfo.getAccountName());
        info.setStatus(status);
//        info.setStoreId(Integer.parseInt(storeId));
//        info.setMerchantId(accountInfo.getMerchantId());
        if (StringUtil.isNotEmpty(id)) {
            info.setId(Integer.parseInt(id));
            examMemberService.updateExamMember(info);
        } else {
            examMemberService.addExamMember(info);
        }

        return getSuccessResult(true);
    }

    /**
     * 获取成员信息表详情
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "获取成员信息表详情")
    @RequestMapping(value = "/info/{id}", method = RequestMethod.GET)
    @CrossOrigin
    @PreAuthorize("@pms.hasPermission('exam_member:list')")
    public ResponseObject info(HttpServletRequest request, @PathVariable("id") Integer id) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        if (accountInfo == null) {
            return getFailureResult(1001, "请先登录");
        }

        MtExamMember exam_memberInfo = examMemberService.queryExamMemberById(id);

        Map<String, Object> result = new HashMap<>();
        result.put("exam_memberInfo", exam_memberInfo);

        return getSuccessResult(result);
    }


    /**
     * 后台查询会员的体检记录（体检项目看不到，通过另一个接口）
     *
     * @param  request HttpServletRequest对象
     * @return 成员信息表列表
     */
    @ApiOperation(value = " 后台查询会员的体检记录（体检项目看不到，通过另一个接口）")
    @RequestMapping(value = "/dataOfBodyExam", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject dataOfBodyExam(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        Integer page = request.getParameter("page") == null ? Constants.PAGE_NUMBER : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));
        String title = request.getParameter("title");
        String searchStoreId = request.getParameter("storeId");

        AccountInfo accountInfo = TokenUtil.getAccountInfoByToken(token);
        Integer storeId = accountInfo.getStoreId();

        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(page);
        paginationRequest.setPageSize(pageSize);

        Map<String, Object> params = new HashMap<>();
        if (accountInfo.getMerchantId() != null && accountInfo.getMerchantId() > 0) {
            params.put("merchantId", accountInfo.getMerchantId());
        }
        if (StringUtil.isNotEmpty(title)) {
            params.put("title", title);
        }
        if (StringUtil.isNotEmpty(searchStoreId)) {
            params.put("storeId", searchStoreId);
        }
        if (storeId != null && storeId > 0) {
            params.put("storeId", storeId);
        }
        paginationRequest.setSearchParams(params);
        PaginationResponse<MtExamMember> paginationResponse = examMemberService.queryExamMemberListByPagination(paginationRequest);

        List<MtExamMember> content = paginationResponse.getContent();
        //所有人的所有体检记录
        ArrayList<ExamDataDTO3> examDataDTO3s = new ArrayList<>();
        content.forEach(mtExamMember -> {
            // 通过身份证查询该成员的所有体检记录
            LambdaQueryWrapper<MtExamRecord> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(MtExamRecord::getExamNo, mtExamMember.getExamNo());
            List<MtExamRecord> mtExamRecords = examRecordMapper.selectList(lambdaQueryWrapper);
            // 一条记录 + 一位成员 → 一条DTO
                ExamDataDTO3 dto = new ExamDataDTO3();
                dto.setMtExamMember(mtExamMember);
                dto.setMtExamRecord(mtExamRecords.get(0));
                examDataDTO3s.add(dto);
        });
        //重新分页模型
        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        Page<MtExamMember> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(examDataDTO3s, pageRequest, pageHelper.getTotal());
        PaginationResponse<ExamDataDTO3> pages = new PaginationResponse(pageImpl, ExamDataDTO3.class);
        pages.setTotalPages(pageHelper.getPages());
        pages.setTotalElements(pageHelper.getTotal());
        pages.setContent(examDataDTO3s);
        Map<String, Object> result = new HashMap<>();
        result.put("paginationResponse", pages);
        return getSuccessResult(result);
    }




    /**
     * 根据体检记录查询具体的体检信息
     *
     * @param  request HttpServletRequest对象
     * @return 成员信息表列表
     */
    @ApiOperation(value = "根据体检记录查询具体的体检信息")
    @RequestMapping(value = "/dataInfoOfBodyExam", method = RequestMethod.GET)
    @CrossOrigin
    public ResponseObject dataInfoOfBodyExam(HttpServletRequest request) throws BusinessCheckException {
        String token = request.getHeader("Access-Token");
        Integer page = request.getParameter("page") == null ? Constants.PAGE_NUMBER : Integer.parseInt(request.getParameter("page"));
        Integer pageSize = request.getParameter("pageSize") == null ? Constants.PAGE_SIZE : Integer.parseInt(request.getParameter("pageSize"));

        //体检id
        String examNo = request.getParameter("examNo");
        // 查询所有设备记录
        List<MtDeviceRecord> mtDeviceRecords = mtDeviceRecordMapper.selectList(
                new LambdaQueryWrapper<MtDeviceRecord>().eq(MtDeviceRecord::getExamNo, examNo)
        );

        // 初始化 DTO 列表
        List<MtDeviceRecordDTO> dtoList = new ArrayList<>();
        for (MtDeviceRecord record : mtDeviceRecords) {
            // 查询当前记录对应的明细项
            List<MtDeviceItem> items = mtDeviceItemMapper.selectList(
                    new LambdaQueryWrapper<MtDeviceItem>().eq(MtDeviceItem::getRecordNo, record.getRecordNo())
            );

            MtDeviceRecordDTO dto = new MtDeviceRecordDTO();
            BeanUtils.copyProperties(record, dto);
            dto.setItems(items);
            dtoList.add(dto);
        }
        PaginationRequest paginationRequest = new PaginationRequest();
        paginationRequest.setCurrentPage(page);
        paginationRequest.setPageSize(pageSize);
        //重新分页模型
        PageRequest pageRequest = PageRequest.of(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        Page<MtDeviceRecordDTO> pageHelper = PageHelper.startPage(paginationRequest.getCurrentPage(), paginationRequest.getPageSize());
        PageImpl pageImpl = new PageImpl(dtoList, pageRequest, pageHelper.getTotal());
        PaginationResponse<MtDeviceRecordDTO> pages = new PaginationResponse(pageImpl, MtDeviceRecordDTO.class);
        pages.setTotalPages(pageHelper.getPages());
        pages.setTotalElements(pageHelper.getTotal());
        pages.setContent(dtoList);
        Map<String, Object> result = new HashMap<>();
        result.put("paginationResponse", pages);
        return getSuccessResult(result);
    }
}
